<?php

namespace app\client;

use Gaoming13\HttpCurl\HttpCurl;
use think\facade\Cache;

class WeChatClient
{
    private $appId = null;
    private $appSecret = null;

    private $url = 'https://api.weixin.qq.com/cgi-bin/';
    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getAccessToken()
    {
        $token = $this->getRedisCache()->get('wechat:access_token');
        if (!empty($token)) {
            return $token;
        }
        $result = $this->request('token', 'get', [
            'grant_type' => 'client_credential',
            'appid' => $this->appId,
            'secret' => $this->appSecret,
        ]);

        $this->getRedisCache()->set('wechat:access_token', $result['access_token'], $result['expires_in']);

        return $result['access_token'];
    }

    public function searchWeCherUserList($nextOpenid = 0)
    {
        $result = $this->request('user/get', 'post', [
            'access_token' => $this->getAccessToken(),
            'next_openid' =>  empty($nextOpenid) ? null: $nextOpenid,
        ]);

        return $result;
    }

    public function findUserInfoByOpenIds(array $userList)
    {
        $result = $this->request(
            'user/info/batchget?access_token='.$this->getAccessToken(),
            'post',
            json_encode([
            'user_list' => $userList
        ])
        );

        return $result;
    }

    public function pushMessage($data)
    {
        $result = $this->request('message/template/send?access_token='.$this->getAccessToken(), 'post', json_encode($data));

        return $result;
    }

    protected function request($prefix, $type, $data = false, $header = [], $timeout = 0)
    {
        $url = $this->url.$prefix;

        list($body, $header, $status, $errno, $error) = HttpCurl::request($url, $type, $data, $header, $timeout);

        if (empty($body)) {
            return [];
        }
        return json_decode($body, true);
    }

    /**
     * @return \think\cache\Driver
     */
    protected function getRedisCache()
    {
        return Cache::store('redis');
    }
}
